package org.point.controller;

import java.io.IOException;
import java.security.interfaces.RSAPrivateKey;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.point.common.controller.BaseController;
import org.point.common.util.DoPage;
import org.point.common.util.MD5Util;
import org.point.common.util.RSAUtils;
import org.point.domain.Member;
import org.point.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSONObject;

/**
 * 
 * @ClassName: MemberController
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author Kenny_Z' szqiuk@gmail.com
 * @date 2016年10月23日 下午9:18:30
 *
 */
@Controller
@RequestMapping("/member/")
public class MemberController extends BaseController{

	@Autowired
	private MemberService service;

	@RequestMapping(value = "memberList.do", method = RequestMethod.POST, produces = "text/plain;charset=UTF-8")
	public void userList(@RequestParam(value = "memberId") String memberId,
			@RequestParam(value = "currentPage") Integer currentPage,
			@RequestParam(value = "status", required = false) String status,
			@RequestParam(value = "keyWord", required = false) String keyWord, HttpServletResponse response) {
		DoPage<Member> page = new DoPage<Member>();
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject jsonObj = new JSONObject();
		try {

			if (strOperateUtil.isNullForString(keyWord)) {
				map.put("keyWord", "%" + keyWord + "%");
			}
			if (strOperateUtil.isNullForString(status)) {
				map.put("status", status);
			}
			if (memberId.trim().length() > 0 && memberId != null) {
				map.put("memberId", memberId);
				if (currentPage != null) {
					map.put("firstRecord", page.getFirstRecord());
					map.put("pageSize", page.getPageSize());
					page.setPageSize(10);
					page.setMap(map);
					// 查询商品分类数据分页返回数据
					DoPage<Member> resultPage = service.searchCRForPage(page);
					// 商品数据分页返回成功及返回状态
					jsonObj.put("page", resultPage);
					jsonObj.put("resultMsg", 1);
				} else {
					jsonObj.put("resultMsg", -2);
				}
			} else {
				// 参数传递错误，会员单位ID为空！
				jsonObj.put("resultMsg", -1);
			}
		} catch (Exception e) {
			// 网络错误，请联系管理员！
			jsonObj.put("resultMsg", 0);
			throw new RuntimeException("商品查询出错!", e);
		} finally {
			try {
				feedback(response, jsonObj.toString());
			} catch (IOException e) {
				throw new RuntimeException("网络错误，请联系管理员！", e);
			}
		}
	}

	@RequestMapping(value = "memberA.do", method = RequestMethod.POST, produces = "text/plain;charset=UTF-8")
	public void isMemberForA(@RequestParam(value = "account") String account, HttpServletResponse response) {
		JSONObject jsonObj = new JSONObject();
		Integer result = 0;
		try {
			if (strOperateUtil.isNullForString(account)) {
				result = service.isLoginA(account);
				jsonObj.put("resultMsg", result);
			} else {
				jsonObj.put("resultMsg", -1);
			}
		} catch (Exception e) {
			jsonObj.put("resultMsg", 0);
			throw new RuntimeException("查询账号是否存在错误！@", e);
		} finally {
			try {
				feedback(response, jsonObj.toString());
			} catch (IOException e) {
				throw new RuntimeException("网络错误，请联系管理员！", e);
			}
		}

	}
    
	/**
	 * 登录
	 *  关于返回值    resultMsg 说明：
	 *  0 异常错误
	 * -1 用户名或者密码不能为空
	 * -2  用户不存在
	 * -3  登录失效
	 * -4  首次登录
	 * @param account
	 * @param password
	 * @param response
	 * @param session
	 */
	@RequestMapping(value = "memberAP.do", produces = "text/plain;charset=UTF-8")
	public void isMemberForAP(@RequestParam(value = "account") String account,
			@RequestParam(value = "password") String password, HttpServletResponse response, HttpSession session) {

		JSONObject jsonObj = new JSONObject();
		Member member = null;
		Integer result = 0;
		try {
			if(strOperateUtil.isNullForString(account)&&strOperateUtil.isNullForString(password)){
				//解析密码
				RSAPrivateKey privateKey = (RSAPrivateKey)getSession().getAttribute("privateKey");  
		        if(privateKey!=null){  
		            /*long time1 = System.currentTimeMillis();*/
		            password = RSAUtils.decryptByPrivateKey(password, privateKey);
		            password = MD5Util.MD5(password);
		            /*logger.info("decrypt cost time:"+(Double)((System.currentTimeMillis()-time1)/1000d) +"s");*/  
		            getSession().removeAttribute("privateKey");
		            member = service.isLoginAP(account, password);
					if(member!=null){
						//是否首次登录 1是 0否 
						if(null!=member.getFirstLogin()&&member.getFirstLogin().equals("1")){
							result=-4;
						}else{
							result=1;
							getSession().setAttribute("users", member);
						}
					}else{
						result=-2;
					}
		        }else{
		        	//登录失效
		        	result=-3;
		        }
				jsonObj.put("resultMsg", result);
			}else{
				jsonObj.put("resultMsg", -1);
			}
		} catch (Exception e) {
			jsonObj.put("resultMsg", 0);
			e.printStackTrace();
			throw new RuntimeException("查询账号是否存在错误！@", e);
		} finally {
			try {
				feedback(response, jsonObj.toString());
			} catch (IOException e) {
				throw new RuntimeException("网络错误，请联系管理员！", e);
			}
		}
	 }
	
	 
	@RequestMapping(value = "memberUpdate.do",produces = "text/plain;charset=UTF-8")
	public void memberUpdate(@RequestParam(value = "phone") String phone, 
			                 @RequestParam(value = "password") String password,
			                 @RequestParam(value = "newPassword") String newPassword,
			                 HttpServletResponse response,HttpSession session){
		JSONObject jsonObj = new JSONObject();
		Integer member =null;
		Integer result=0;
		try {
			if(strOperateUtil.isNullForString(phone)&&strOperateUtil.isNullForString(password)&&strOperateUtil.isNullForString(newPassword)){
				// 解析密码
				RSAPrivateKey privateKey = (RSAPrivateKey) session.getAttribute("privateKey");
				if (privateKey != null) {
					long time1 = System.currentTimeMillis();
					password = RSAUtils.decryptByPrivateKey(password, privateKey);
					logger.info("decrypt cost time:" + (Double) ((System.currentTimeMillis() - time1) / 1000d) + "s");
					session.removeAttribute("privateKey");
				}
		        Map<String, Object> map = new HashMap<String, Object>();
				map.put("phone", phone);
				map.put("password", password);
				map.put("newPassword", newPassword);
				member = service.updateMemberPwd(map);
				
				if (member != null) {
					result = 1;
					session.removeAttribute("users");
				} else {
					result = -2;
				}
				jsonObj.put("resultMsg", result);
			} else {
				jsonObj.put("resultMsg", -1);
			}
		} catch (Exception e) {
			jsonObj.put("resultMsg", 0);
			e.printStackTrace();
			throw new RuntimeException("查询账号是否存在错误！@", e);
		} finally {
			try {
				feedback(response, jsonObj.toString());
			} catch (IOException e) {
				throw new RuntimeException("网络错误，请联系管理员！", e);
			}
		}

	 }
	 

}
